﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace A2DFramework.RuleEngine
{
    class JavascriptGenerator : IJavascriptGenerator
    {
        private string ruleContent;

        public void SetRuleContent(string ruleContent)
        {
            this.ruleContent = ruleContent;
        }

        public string GenerateJS()
        {
            string js = "";
            js = this.GeneratePreservedJS() + "\r\n" + this.GenerateGlobalDeclareJS(ruleContent) + "\r\n" + this.GenerateJudgeJS(ruleContent);
            return js;
        }
        private string GenerateGlobalDeclareJS(string ruleContent)
        {
            Declare declare = Parser.ParseDeclare(ruleContent);
            string jsTotal = string.Empty;

            foreach (string line in declare.Declares)
                jsTotal += line + ";\r\n";

            return jsTotal;
        }
        private string GenerateJudgeJS(string ruleContent)
        {
            List<Rule> rules = Parser.ParseRules(ruleContent);
            string jsTotal = string.Empty;
            for (int i = 0; i < rules.Count; i++)
            {
                Rule rule = rules[i];

                string js = string.Empty;
                foreach (string when in rule.Whens)
                    js += string.Format("({0})&&", when);
                js = js.TrimEnd("&&".ToCharArray());
                js = string.Format("if({0})\r\n", js);
                js += "{\r\n";
                foreach (string then in rule.Thens)
                    js += string.Format("{0};\r\n", then);
                js += "}\r\n";

                if (i == 0)
                    jsTotal += "\r\n" + js;
                else
                    jsTotal += "else " + js;
            }

            return jsTotal;
        }

        private string GeneratePreservedJS()
        {
            string path=System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RuleEngine", "jsLib", "underscore-min.js");
            string libJsContent=File.ReadAllText(path);
            return libJsContent + "\r\n\r\n\r\n";
        }

    }
}
